package com.sgb.knowledgeshare.weight;

import android.content.Context;
import android.graphics.Color;
import android.graphics.SurfaceTexture;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.FrameLayout;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.aliyun.player.AliListPlayer;
import com.aliyun.player.AliPlayerFactory;
import com.aliyun.player.IPlayer;
import com.aliyun.player.bean.ErrorInfo;
import com.sgb.knowledgeshare.R;
import com.swgk.core.base.model.entity.VideoBean;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by：冯齐 on 2020/12/6 15:34
 * Description： 视频列表处理
 */
public class AlivcVideoListView extends FrameLayout {

    private final Context mContext;
    private List<VideoBean> list;
    private View mPlayerViewContainer;
    private TextureView mTextureView;
    private GestureDetector gestureDetector;
    private AliListPlayer mListPlayer;
    private RecyclerView recycler;
    private VideoSwipeRefreshLayout refreshView;
    private RecyclerView.RecycledViewPool mRecycledViewPool;
    private PagerLayoutManager pagerLayoutManager;
    /**
     * 当前选中位置
     */
    private int mCurrentPosition;

    /**
     * 正常滑动，上一个被暂停的位置
     */
    private int mLastStopPosition = -1;
    private BaseVideoListAdapter adapter;
    /**
     * 是否点击暂停
     */
    private boolean isPause = false;
    private ImageView mPlayIcon;
    /**
     * 判断是否处于加载数据的状态中
     */
    private boolean isLoadingData;

    /**
     * 预加载位置, 默认离底部还有2条数据时请求下一页视频列表
     */
    private static final int DEFAULT_PRELOAD_NUMBER = 2;
    /**
     * 当前页面是否处于可见状态
     */
    private boolean isOnBackground = true;
    /**
     * 数据是否到达最后一页
     */
    private boolean isEnd;
    /**
     * 刷新数据listener
     */
    private OnRefreshDataListener onRefreshDataListener;

    /**
     * 当前播放视频的id
     */
    private String VideoId = "";


    public AlivcVideoListView(@NonNull Context context) {
        super(context);
        this.mContext = context;
        initPlayer();
        initData();
    }

    /**
     * 初始化播放器相关
     */
    private void initPlayer() {
        mPlayerViewContainer = View.inflate(getContext(), R.layout.video_player_view, null);
        mTextureView = mPlayerViewContainer.findViewById(R.id.video_textureview);
      /*  gestureDetector = new GestureDetector(mContext,
                new GestureDetector.SimpleOnGestureListener() {

                    @Override
                    public boolean onSingleTapConfirmed(MotionEvent e) {
                        //判断当前view是否可见，防止退后台、切换页面和单击同时操作导致，退后台时视频又重新开始播放
                        if (AlivcVideoListView.this.isShown()) {
                            onPauseClick();
                        }
                        return true;
                    }

                    @Override
                    public boolean onDown(MotionEvent e) {
                        return true;
                    }
                });
        mPlayerViewContainer.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return gestureDetector.onTouchEvent(event);
            }
        });*/
        mTextureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
            @Override
            public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
                Surface mSurface = new Surface(surface);
                if (mListPlayer != null) {
                    mListPlayer.setSurface(mSurface);
                    mListPlayer.redraw();
                }
            }

            @Override
            public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
                if (mListPlayer != null) {
                    mListPlayer.redraw();
                }
            }

            @Override
            public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
                if (mListPlayer != null) {
                    mListPlayer.setSurface(null);
                }
                return true;
            }

            @Override
            public void onSurfaceTextureUpdated(SurfaceTexture surface) {

            }
        });
        mListPlayer = AliPlayerFactory.createAliListPlayer(mContext);
        mListPlayer.setLoop(true);
        mListPlayer.setAutoPlay(false);
        mListPlayer.setPreloadCount(10);
        //   mListPlayer.setScaleMode(IPlayer.ScaleMode.SCALE_ASPECT_FIT);
        mListPlayer.setOnPreparedListener(new IPlayer.OnPreparedListener() {
            @Override
            public void onPrepared() {
                //准备成功事件
                if (!isPause && !isOnBackground) {
                    mListPlayer.start();
                }
            }
        });
        mListPlayer.setOnRenderingStartListener(new IPlayer.OnRenderingStartListener() {
            @Override
            public void onRenderingStart() {
                //首帧渲染显示事件   隐藏封面
                BaseVideoListAdapter.BaseHolder holder = (BaseVideoListAdapter.BaseHolder) recycler.findViewHolderForLayoutPosition(mCurrentPosition);
                if (holder != null) {
                    holder.getCoverView().setVisibility(GONE);
                }
                if (mLoadingListener != null) {
                    mLoadingListener.onLoadingEnd();
                }
            }
        });
        mListPlayer.setOnLoadingStatusListener(new IPlayer.OnLoadingStatusListener() {
            @Override
            public void onLoadingBegin() {
                //缓冲开始。
                if (mLoadingListener != null) {
                    mLoadingListener.onLoadingBegin();
                }
            }

            @Override
            public void onLoadingEnd() {
                //缓冲结束
                if (mLoadingListener != null) {
                    mLoadingListener.onLoadingEnd();
                }
            }

            @Override
            public void onLoadingProgress(int percent, float netSpeed) {
                //缓冲进度
                if (mLoadingListener != null) {
                    mLoadingListener.onLoadingProgress(percent, netSpeed);
                }
            }
        });
        mListPlayer.setOnErrorListener(new IPlayer.OnErrorListener() {
            @Override
            public void onError(ErrorInfo errorInfo) {
                //出错事件
                Log.e("tag视频出错了", errorInfo.getMsg() + " --- " + errorInfo.getCode());
            }
        });
    }

    private IPlayer.OnLoadingStatusListener mLoadingListener;

    public void setLoadingListener(IPlayer.OnLoadingStatusListener mLoadingListener) {
        this.mLoadingListener = mLoadingListener;
    }

    public void setOnRefreshDataListener(OnRefreshDataListener onRefreshDataListener) {
        this.onRefreshDataListener = onRefreshDataListener;
    }

    private void initData() {
        list = new ArrayList<>();
        View view = LayoutInflater.from(mContext).inflate(R.layout.share_video_list, this, true);
        recycler = view.findViewById(R.id.recycler);
        refreshView = view.findViewById(R.id.refresh_view);
        refreshView.setColorSchemeColors(Color.YELLOW, Color.GREEN, Color.BLUE, Color.RED);
        refreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (onRefreshDataListener != null) {
                    isLoadingData = true;
                    onRefreshDataListener.onRefresh();
                }
            }
        });
        recycler.setHasFixedSize(true);
        mRecycledViewPool = new RecyclerView.RecycledViewPool();
        mRecycledViewPool.setMaxRecycledViews(0, 50);
        recycler.setRecycledViewPool(mRecycledViewPool);
        pagerLayoutManager = new PagerLayoutManager(mContext);
        pagerLayoutManager.setItemPrefetchEnabled(true);
        recycler.setLayoutManager(pagerLayoutManager);
        //  recycler.setEmptyView(view.findViewById(R.id.ll_empty_view));
        pagerLayoutManager.setOnViewPagerListener(new PagerLayoutManager.OnViewPagerListener() {
            @Override
            public void onInitComplete() {
                int position = pagerLayoutManager.findFirstVisibleItemPosition();
                if (position != -1) {
                    mCurrentPosition = position;
                }
                int itemCount = adapter.getItemCount();
                if (itemCount - position < DEFAULT_PRELOAD_NUMBER && !isLoadingData && !isEnd) {
                    // 正在加载中, 防止网络太慢或其他情况造成重复请求列表
                    isLoadingData = true;
                    loadMore();
                }
                startPlay(mCurrentPosition);
                mLastStopPosition = -1;

            }

            @Override
            public void onPageRelease(boolean isNext, int position) {

                if (mCurrentPosition == position) {
                    mLastStopPosition = position;
                    stopPlay();
                    BaseVideoListAdapter.BaseHolder holder = (BaseVideoListAdapter.BaseHolder) recycler.findViewHolderForLayoutPosition(position);
                    if (holder != null) {
                        holder.getCoverView().setVisibility(VISIBLE);
                        if (holder.getPlayIcon() != null) {
                            holder.getPlayIcon().setVisibility(View.GONE);
                        }
                    }
                }

            }

            @Override
            public void onPageSelected(int position, boolean b) {
                //重新选中视频不播放，如果该位置被stop过则会重新播放视频
                if (mCurrentPosition == position && mLastStopPosition != position) {
                    return;
                }

                int itemCount = adapter.getItemCount();
                if (itemCount - position < DEFAULT_PRELOAD_NUMBER && !isLoadingData && !isEnd) {
                    // 正在加载中, 防止网络太慢或其他情况造成重复请求列表
                    isLoadingData = true;
                    loadMore();
                }
                if (itemCount == position + 1 && isEnd) {
                    //  Toast.makeText(getContext(), "已经是最后一个视频了", Toast.LENGTH_SHORT).show();
                }
                //开始播放选中视频
                startPlay(position);
                mCurrentPosition = position;
            }
        });
    }

    /**
     * 开始播放
     *
     * @param position 播放位置
     */
    private void startPlay(int position) {
        if (position < 0 || position > list.size()) {
            return;
        }
        VideoBean video = list.get(position);
        if (video.getVideoId() != null)
            Log.e("tag视频播放id", video.getVideoId());
        //恢复界面状态
        isPause = false;
        BaseVideoListAdapter.BaseHolder holder = (BaseVideoListAdapter.BaseHolder) recycler.findViewHolderForLayoutPosition(position);
        if (holder != null) {
            mPlayIcon = holder.getPlayIcon();
            mPlayIcon.setVisibility(View.GONE);
        }
        ViewParent parent = mPlayerViewContainer.getParent();
        if (parent != null && parent instanceof FrameLayout) {
            ((ViewGroup) parent).removeView(mPlayerViewContainer);
        }
        callback.VideoInfo(position, video);
        VideoId = video.getVideoId();
        Log.e("tag视频id", VideoId + "");
        if (holder != null) {
            holder.getContainerView().addView(mPlayerViewContainer, 0);
        }
        if (position - mCurrentPosition == 1) {
            mListPlayer.moveToNext();
        } else if (position - mCurrentPosition == -1) {
            mListPlayer.moveToPrev();
        } else {
            mListPlayer.moveTo(video.getVideoId());
        }
    }


    /**
     * 停止视频播放
     */
    private void stopPlay() {
        ViewParent parent = mPlayerViewContainer.getParent();
        if (parent != null && parent instanceof FrameLayout) {
            ((FrameLayout) parent).removeView(mPlayerViewContainer);
        }
        mListPlayer.stop();
        mListPlayer.setSurface(null);
    }

    /**
     * 视频暂停/恢复的时候使用，
     */
    public void onPauseClick() {
        if (isPause) {
            resumePlay();
        } else {
            pausePlay();
        }
    }

    /**
     * 恢复播放
     */
    private void resumePlay() {
        isPause = false;
        if (mPlayIcon != null) {
            mPlayIcon.setVisibility(View.GONE);
        }

        mListPlayer.start();
    }


    /**
     * 暂停播放
     */
    private void pausePlay() {
        isPause = true;
        if (mPlayIcon != null) {
            mPlayIcon.setVisibility(View.VISIBLE);
        }
        mListPlayer.pause();

    }

    /**
     * 设置播放器数量
     *
     * @param playerCount
     */
    public void setPlayerCount(int playerCount) {

        mListPlayer.setPreloadCount(playerCount);
    }

    /**
     * activity不可见或者播放页面不可见时调用该方法
     */
    public void setOnBackground(boolean isOnBackground) {
        this.isOnBackground = isOnBackground;
        if (isOnBackground) {
            pausePlay();
        } else {
            resumePlay();
        }
    }

    /**
     * 加载更多
     */
    private void loadMore() {
        if (onRefreshDataListener != null) {
            onRefreshDataListener.onLoadMore();
        }
    }

    /**
     * 设置adapter
     *
     * @param adapter
     */
    public void setAdapter(BaseVideoListAdapter adapter) {
        this.adapter = adapter;
        recycler.setAdapter(adapter);
        this.list = adapter.getDataList();
    }

    /**
     * 刷新数据
     *
     * @param list 刷新数据
     */
    public void refreshData(List<VideoBean> list) {
        clearNotShowVideo(list);
        if (refreshView != null && refreshView.isRefreshing()) {
            refreshView.setRefreshing(false);
            // 加载完毕, 重置加载状态
        }
        if (mListPlayer != null) {
            mListPlayer.clear();
            for (VideoBean iVideoSourceModel : list) {
                String url = iVideoSourceModel.getCoverURL();
                String uuid = iVideoSourceModel.getVideoId();
                mListPlayer.addUrl(url, uuid);
            }
        }
        isEnd = false;
        isLoadingData = false;
        adapter.refreshData(list);
    }

    /**
     * 刷新数据，并播放指定位置的视频
     *
     * @param list     视频列表数据
     * @param position 刷新完成之后播放位置
     */
    public void refreshData(List<VideoBean> list, int position) {
        int size = list.size();
        if (position < 0) {
            position = 0;
        }
        if (size <= position) {
            position = size - 1;
        }
        mCurrentPosition = position;
        refreshData(list);
        recycler.scrollToPosition(mCurrentPosition);

    }

    /**
     * 加载更多数据
     *
     * @param list
     */
    public void addMoreData(List<VideoBean> list) {
        if (list == null || list.size() < 10) {
            isEnd = true;
        } else {
            isEnd = false;
        }
        clearNotShowVideo(list);
        isLoadingData = false;
        if (adapter != null) {
            adapter.addMoreData(list);
        }
        if (mListPlayer != null) {
            for (VideoBean iVideoSourceModel : list) {
                mListPlayer.addUrl(iVideoSourceModel.getCoverURL(), iVideoSourceModel.getVideoId());
            }
        }
        if (refreshView.isRefreshing()) {
            refreshView.setRefreshing(false);
        }

    }

    /**
     * 修改数据源状态
     *
     * @param list
     */
    private void clearNotShowVideo(List<VideoBean> list) {
        for (VideoBean at : list) {
            if (at.getIsLaud() == 0) {// 是否点赞（0：不是，1：是）
                at.setLiked(false);
            } else {
                at.setLiked(true);
            }
        }
    }

    /**
     * 视频列表获取失败
     */
    public void loadFailure() {
        if (refreshView.isRefreshing()) {
            refreshView.setRefreshing(false);
        }
    }

    /**
     * 恢复视频播放
     */
    public void setRecoverVideoPlay() {
        resumePlay();
    }

    /**
     * 暂停视频播放
     */
    public void setPauseVideoPlay() {
        pausePlay();
    }

    /**
     * 设置视频播放位置
     *
     * @param i
     */
    public void setPlayVideoIndex(String i) {
       /* if (pagerLayoutManager != null) {
            pagerLayoutManager.scrollToPosition(i);
        }*/
    /*    recycler.scrollToPosition(i);
        pagerLayoutManager.scrollToPosition(i);*/
        mListPlayer.moveTo(i);
    }

    /**
     * 初始化视频播放源
     *
     * @param videoBean
     */
    public void setVideoList(List<VideoBean> videoBean) {
        if (videoBean != null) {
            refreshData(videoBean);
        }
    }

    /**
     * 是否可垂直滑动
     *
     * @param scroll
     */
    public void onCanVerticalScroll(boolean scroll) {
        if (pagerLayoutManager != null) {
            pagerLayoutManager.setCanVerticalScroll(scroll);
        }
    }

    /**
     * 视频是否暂停或者播放
     */
    public void onPlayOrPause() {
        if (AlivcVideoListView.this.isShown()) {
            onPauseClick();
        }
    }

    /**
     * 刷新数据
     */
    public interface OnRefreshDataListener {
        /**
         * 下拉刷新
         */
        void onRefresh();

        /**
         * 上拉加载
         */
        void onLoadMore();
    }

    private PlayVideoListInfo callback;

    public void setCallback(PlayVideoListInfo callback) {
        this.callback = callback;
    }

    public interface PlayVideoListInfo {
        //视频详情
        void VideoInfo(int pos, VideoBean video);
    }

}
